package com.jinjunhuang.memoryopt;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.lang.ref.WeakReference;

/**
 * @author jianjunhuang.me@foxmail.com
 *         create on 2017/11/16.
 */

public class HandlerFitActivity extends AppCompatActivity implements View.OnClickListener{

    private Button handlerFitBtn;

    private MHandler mHandler;

    private MRunnable mRunnable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handler_fit_activity);
        handlerFitBtn = findViewById(R.id.handler_fit_btn);
        mHandler = new MHandler(this);
        mRunnable = new MRunnable(this);
        handlerFitBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        mHandler.postDelayed(mRunnable, 1000);
        mHandler.sendEmptyMessage(0);
    }

    static class MHandler extends Handler {
        WeakReference<Activity> mActivityWeakReference;

        MHandler(Activity activity) {
            mActivityWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
//            Toast.makeText(mActivityWeakReference.get(), "haha", Toast.LENGTH_LONG).show();
        }
    }

    static class MRunnable implements Runnable {

        private WeakReference<Activity> mActivityWeakReference;

        public MRunnable(Activity activity) {
            mActivityWeakReference = new WeakReference<Activity>(activity);
        }

        @Override
        public void run() {
//            Toast.makeText(mActivityWeakReference.get(), ">>>>>>>", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler = null;
        mRunnable = null;
    }
}
